package com.ticket.system.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ticket.common.annotation.DataScope;
import com.ticket.common.constant.Constants;
import com.ticket.common.constant.UserConstants;
import com.ticket.common.core.domain.TreeSelect;
import com.ticket.common.core.domain.entity.SysDept;
import com.ticket.common.core.domain.entity.SysRole;
import com.ticket.common.core.domain.entity.SysUser;
import com.ticket.common.core.text.Convert;
import com.ticket.common.exception.ServiceException;
import com.ticket.common.exception.base.BaseException;
import com.ticket.common.utils.Const;
import com.ticket.common.utils.SecurityUtils;
import com.ticket.common.utils.StringUtils;
import com.ticket.common.utils.spring.SpringUtils;
import com.ticket.system.domain.SysUserRole;
import com.ticket.system.domain.TYanchuClassify;
import com.ticket.system.domain.YanchuPerform;
import com.ticket.system.domain.YanchuSession;
import com.ticket.system.domain.vo.DeptVo;
import com.ticket.system.domain.vo.SessionAndTicket;
import com.ticket.system.mapper.*;
import com.ticket.system.service.ISysDeptService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import static com.ticket.common.utils.PageUtils.startPage;

/**
 * 部门管理 服务实现
 * 
 * @author ruoyi
 */
@Service
public class SysDeptServiceImpl implements ISysDeptService
{

    private static final Logger log = LoggerFactory.getLogger(SysDeptServiceImpl.class);

    private static final String ONEOPERA = "集团管理员";
    private static final String TWOOPERA = "剧院管理员";

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private SysRoleMapper roleMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysUserRoleMapper userRoleMapper;
    @Autowired
    private YanchuSessionMapper yanchuSessionMapper;
    @Autowired
    private YanchuPerformMapper yanchuPerformMapper;
    @Autowired
    private TYanchuClassifyMapper tYanchuClassifyMapper;
    @Autowired
    private YanchuTicketPriceMapper yanchuTicketPriceMapper;

    /**
     * 查询部门管理数据
     * 
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> selectDeptList(SysDept dept)
    {
        return deptMapper.selectDeptList(dept);
    }

    /**
     * 查询部门树结构信息
     * 
     * @param dept 部门信息
     * @return 部门树信息集合
     */
    @Override
    public List<TreeSelect> selectDeptTreeList(SysDept dept)
    {
        List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);
        return buildDeptTreeSelect(depts);
    }

    /**
     * 查询部门树结构信息
     *
     * @param dept 部门信息
     * @return 部门树信息集合
     */
    @Override
    public List<TreeSelect> getDeptTreeList(SysDept dept){
        SysDept deptOne = new SysDept();
        deptOne.setOperaId(dept.getDeptId());
        deptOne.setDeptName(null);
        deptOne.setStatus(null);
        List<SysDept> depts = selectDeptLists(deptOne);
        depts.add(dept);
        List<SysDept> collect = depts.stream().sorted(Comparator.comparing(SysDept::getDeptType).reversed()).collect(Collectors.toList());
        return buildDeptTreeSelect(collect);
    }

    /**
     * 构建前端所需要树结构
     * 
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDept> buildDeptTree(List<SysDept> depts)
    {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<Long> tempList = depts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
        for (SysDept dept : depts)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId()))
            {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     * 
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts)
    {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据角色ID查询部门树信息
     * 
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<Long> selectDeptListByRoleId(Long roleId)
    {
        SysRole role = roleMapper.selectRoleById(roleId);
        return deptMapper.selectDeptListByRoleId(roleId, role.isDeptCheckStrictly());
    }

    /**
     * 根据部门ID查询信息
     * 
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public SysDept selectDeptById(Long deptId)
    {
        SysDept sysDept = deptMapper.selectDeptById(deptId);
        List<SysUser> users = userMapper.getUserByDeptId(deptId);
        if (CollectionUtils.isNotEmpty(users)){
             sysDept.setLoginName(users.get(0).getUserName());
        }
        return sysDept;
    }

    public List<Long> getChildOperList(Long deptId){
        if(deptId==null){
            return null;
        }
        SysDept sysDept = new SysDept();
        sysDept.setDeptId(deptId);
        List<SysDept> sysDepts = deptMapper.selectAll();
        List<Long> deptList = new ArrayList<>();
        deptList.add(deptId);
        getAllChild(sysDepts,deptId,deptList);
        return deptList;
    }

    public void getAllChild(List<SysDept> depts,Long pid, List<Long> deptList){
        for (SysDept dept : depts) {
            if(dept.getParentId().equals(pid)){
                getAllChild(depts,dept.getDeptId(),deptList);
                deptList.add(dept.getDeptId());
            }
        }
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     * 
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenDeptById(Long deptId)
    {
        return deptMapper.selectNormalChildrenDeptById(deptId);
    }

    /**
     * 是否存在子节点
     * 
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(Long deptId)
    {
        int result = deptMapper.hasChildByDeptId(deptId);
        return result > 0;
    }

    /**
     * 查询部门是否存在用户
     * 
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId)
    {
        int result = deptMapper.checkDeptExistUser(deptId);
        return result > 0;
    }

    /**
     * 校验部门名称是否唯一
     * 
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public boolean checkDeptNameUnique(SysDept dept)
    {
        SysDept sysDept = deptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getOperaId());
        return Optional.ofNullable(sysDept).isPresent();
    }

    /**
     * 校验部门是否有数据权限
     * 
     * @param deptId 部门id
     */
    @Override
    public void checkDeptDataScope(Long deptId)
    {
        if (!SysUser.isAdmin(SecurityUtils.getUserId()))
        {
            SysDept dept = new SysDept();
            dept.setDeptId(deptId);
            List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);
            if (StringUtils.isEmpty(depts))
            {
                throw new ServiceException("没有权限访问部门数据！");
            }
        }
    }

    /**
     * 新增保存部门信息
     * 
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public int insertDept(SysDept dept)
    {
        //剧院
        if (Const.ONE.equals(dept.getDeptType())){
            if (this.checkDeptNameOpera(dept)) {
                throw new BaseException("新增剧院'" + dept.getDeptName() + "'失败，剧院名称已存在");
            }
            if (StringUtils.isEmpty(dept.getLoginName())){
                throw new BaseException("管理员账号不能为空");
            }
            if (null != userMapper.checkUserNameUnique(dept.getLoginName())){
                throw new BaseException("当前管理员账号已存在");
            }
            if (StringUtils.isEmpty(dept.getPassWord())){
                throw new BaseException("管理员密码不能为空");
            }
            if (StringUtils.isNotNull(dept.getParentId())){
                if (0 == dept.getParentId()){
                    dept.setOperaLevel(1);
                }else {
                    //获取当前剧院级别
                    SysDept info = deptMapper.selectDeptById(dept.getParentId());
                    if (3 <= info.getOperaLevel()){
                        throw new BaseException("上级剧院为三级,不可新增,重新选择上级剧院");
                    }else {
                        dept.setOperaLevel(info.getOperaLevel() + 1);
                    }
                }
            }
        }
        //部门
        if (Const.ZERO.equals(dept.getDeptType()) && this.checkDeptNameUnique(dept)){
            throw new BaseException("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        if (0 != dept.getParentId()) {
            SysDept info = deptMapper.selectDeptById(dept.getParentId());
            // 如果父节点不为正常状态,则不允许新增子节点
            if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
                throw new ServiceException("部门停用，不允许新增");
            }
            dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        }else {
            if (Const.ONE.equals(dept.getDeptType())){
                dept.setAncestors("0");
                dept.setParentId(0L);
            }else {
                SysDept info = deptMapper.selectDeptById(dept.getOperaId());
                dept.setAncestors(info.getAncestors() + "," + dept.getOperaId());
                dept.setParentId(info.getOperaId());
            }
        }
        if (null == dept.getParentId() && StringUtils.isNotNull(dept.getOperaId())) {
            //新增部门
            dept.setParentId(dept.getOperaId());
        }
        int i = deptMapper.insertDept(dept);
        if (Const.ONE.equals(dept.getDeptType())){
            //将管理员账号加入用户表
            SysUser user = new SysUser();
            user.setDeptId(dept.getDeptId());
            user.setUserName(dept.getLoginName());
            user.setUserType("01");
            user.setNickName(dept.getLoginName());
            user.setPassword(SecurityUtils.encryptPassword(dept.getPassWord()));
            user.setCreateBy(dept.getCreateBy());
            if (StringUtils.isNotNull(dept.getOperaId())) {
                user.setOperaId(dept.getOperaId());
            }else {
                user.setOperaId(dept.getDeptId());
            }
            userMapper.insertUser(user);
            SysRole role = new SysRole();
            if (1 == dept.getOperaLevel()){
                role.setRoleName(ONEOPERA);
            }else {
                role.setRoleName(TWOOPERA);
            }
            role.setRoleType(dept.getOperaLevel());
            List<SysRole> sysRoles = roleMapper.selectRoleList(role);
            if (CollectionUtils.isEmpty(sysRoles)){
                throw new BaseException("当前剧院为"+dept.getOperaLevel()+"级剧院,该级别剧院不存在管理员角色。");
            }
            SysUserRole userRole = new SysUserRole();
            userRole.setRoleId(sysRoles.get(0).getRoleId());
            userRole.setUserId(user.getUserId());
            //添加用户角色关联表
            return userRoleMapper.batchUserRole(Collections.singletonList(userRole));
        }
        return i;
    }

    @Override
    public Boolean checkDeptNameOpera(SysDept dept) {
        if (StringUtils.isNotNull(dept.getDeptId())) {
            SysDept sysDept = deptMapper.selectDeptById(dept.getDeptId());
            if (dept.getDeptName().equals(sysDept.getDeptName())) {
                return false;
            }
        }
        Integer integer = deptMapper.checkDeptNameOpera(dept.getDeptName());
        integer = StringUtils.isNull(integer) ? 0 : integer;
        return integer > 0;
    }

    /**
     * 修改保存部门信息
     * 
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int updateDept(SysDept dept)
    {
        SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId());
        SysDept oldDept = deptMapper.selectDeptById(dept.getDeptId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept))
        {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        int result = deptMapper.updateDept(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()) && StringUtils.isNotEmpty(dept.getAncestors())
                && !StringUtils.equals("0", dept.getAncestors()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }
        return result;
    }

    /**
     * 修改该部门的父级部门状态
     * 
     * @param dept 当前部门
     */
    private void updateParentDeptStatusNormal(SysDept dept)
    {
        String ancestors = dept.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        deptMapper.updateDeptStatusNormal(deptIds);
    }

    /**
     * 修改子元素关系
     * 
     * @param deptId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors)
    {
        List<SysDept> children = deptMapper.selectChildrenDeptById(deptId);
        for (SysDept child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            deptMapper.updateDeptChildren(children);
        }
    }

    /**
     * 删除部门管理信息
     * 
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public int deleteDeptById(Long deptId)
    {
        return deptMapper.deleteDeptById(deptId);
    }

    /**
     * 剧院列表
     *
     * @param deptId
     */
    @Override
    public List<SysDept> operaList(Long deptId,Long child) {
        List<SysDept> sysDepts = deptMapper.operaList(deptId,null,child);
        if (CollectionUtils.isNotEmpty(sysDepts)){
            List<Long> parIds = sysDepts.stream().map(SysDept::getParentId).distinct().collect(Collectors.toList());
            List<SysDept> depts = deptMapper.selectDeptByIds(parIds);
            if (CollectionUtils.isNotEmpty(depts)){
                sysDepts.forEach(d -> {
                    depts.forEach(c -> {
                        if (d.getParentId().equals(c.getDeptId())){
                            d.setParentName(c.getDeptName());
                        }
                    });
                });
            }
        }
        return sysDepts;
    }

    @Override
    public List<DeptVo> theatreList(){
        List<DeptVo> list = deptMapper.selectAllTheatre();
        return listToMap(Constants.DEPT_ROOT,list);
    }

    /**
     * 演出获取剧院列表
     *
     * @param operaId
     * @return
     */
    @Override
    public List<SysDept> operaByPlan(Long operaId,String keyName,Long child) {
        SysDept sysDept = deptMapper.selectDeptById(operaId);
        if (Const.ONE.equals(sysDept.getOperaLevel())){
            //省级管理员  查自己包括所有子级
            return deptMapper.operaList(operaId,keyName,child);
        } else {
            //市县管理员  只查自己的
            return Collections.singletonList(deptMapper.getDeptById(operaId,keyName));
        }
    }

    @Override
    public List<SysDept> operaTableByPlan(Long operaId,String keyName,Long child) {
        return deptMapper.operaList(operaId,keyName,child);
    }

    /**
     * 获取所有剧院
     *
     * @return
     */
    @Override
    public List<SysDept> getOperaListAll(String keyName) {
        return deptMapper.getOperaListAll(keyName);
    }

    @Override
    public SysDept getOperaInfo(Long operaId) {
        SysDept sysDept = deptMapper.selectDeptById(operaId);
        if (null == sysDept || !Const.ONE.equals(sysDept.getDeptType())){
            throw new BaseException("不存在该剧院");
        }
        //补充详情下的演出场次
        //获取该剧院下存在售票中的演出
        YanchuPerform perform = new YanchuPerform();
        perform.setOperaId(operaId);
        perform.setType(2);
        List<YanchuPerform> vos = yanchuPerformMapper.selectYanchuPerformList(perform);
        if (CollectionUtils.isNotEmpty(vos)){
            List<Long> onSaleIds = vos.stream().map(YanchuPerform::getId).distinct().collect(Collectors.toList());
            //获取演出信息
            List<YanchuPerform> performs = yanchuPerformMapper.selectPerformByIds(onSaleIds);
            //分类信息
            List<Long> typeIds = performs.stream().map(YanchuPerform::getPerformType).collect(Collectors.toList());
            List<TYanchuClassify> classifies = tYanchuClassifyMapper.selectTYanchuClassifyByIds(typeIds);
            //在售场次id
            List<YanchuSession> onSale = yanchuSessionMapper.getOnSale(operaId);
            if (CollectionUtils.isEmpty(onSale)){
                return sysDept;
            }
            List<Long> sessionIds = onSale.stream().map(YanchuSession::getId).distinct().collect(Collectors.toList());
            //获取演出价格区间
            List<SessionAndTicket> price = yanchuTicketPriceMapper.getPrice(onSaleIds,sessionIds);
            //获取演出时间区间
            List<SessionAndTicket> time = yanchuSessionMapper.getTime(onSaleIds,sessionIds);
            //获取实名标签
            List<Long> autType = yanchuSessionMapper.getAutType(onSaleIds,sessionIds);
            //获取电子票类标签
            List<Long> isTickets = yanchuSessionMapper.getIsTickets(onSaleIds,sessionIds);
            performs.forEach(p ->{
                classifies.forEach(c ->{
                    if (p.getPerformType().equals(c.getId())){
                        p.setPerformTypeName(c.getClassifyName());
                    }
                });
                if (CollectionUtils.isNotEmpty(price)){
                    price.forEach(p1 ->{
                        if (p.getId().equals(p1.getPerformId())){
                            p.setMaxPrice(p1.getMaxPrice());
                            p.setMinPrice(p1.getMinPrice());
                        }
                    });
                }
                if (CollectionUtils.isNotEmpty(time)){
                    time.forEach(t ->{
                        if (p.getId().equals(t.getPerformId())){
                            p.setStartTime(t.getStartTime());
                            p.setEndTime(t.getEndTime());
                        }
                    });
                }
                if (CollectionUtils.isNotEmpty(autType)){
                    if (autType.contains(p.getId())){
                        p.setAutType(1);
                    }else {
                        p.setAutType(2);
                    }
                }else {
                    p.setAutType(2);
                }
                if (CollectionUtils.isNotEmpty(isTickets)){
                    if (isTickets.contains(p.getId())){
                        p.setIsTickets(1);
                    }else {
                        p.setIsTickets(2);
                    }
                }else {
                    p.setIsTickets(2);
                }
            });
            sysDept.setPerforms(JSONObject.toJSONString(performs));
            sysDept.setPerFormNum(performs.size());
        }
        return sysDept;
    }

    /**
     * 详细信息
     *
     * @param deptId
     * @return
     */
    @Override
    public SysDept getDeptInfoById(Long deptId) {
        return deptMapper.selectDeptById(deptId);
    }

    /**
     * 父级信息
     *
     * @param deptId
     * @return
     */
    @Override
    public SysDept getParent(Long deptId) {
        return deptMapper.getParent(deptId);
    }

    private List<DeptVo> listToMap(Long parentId,List<DeptVo> list){
        List<DeptVo> rootList = list.stream()
                // 筛选父节点
                .filter(t -> t.getParentId().equals(parentId))
                // 递归设置子节点
                .map(item -> {
                    item.setChildren(listToMap(item.getDeptId(), list));
                    return item;
                })
                .collect(Collectors.toList());
        return rootList;
    }



    @Override
    public SysDept getOperaDept(Long deptId){
        //当前用户部门获取所在最底级剧院
        SysDept sysDept = deptMapper.selectDeptById(deptId);
        if (0 == sysDept.getParentId()){
            return sysDept;
        }
        String ancestors = sysDept.getAncestors();
        List<Long> deptIds = Arrays.stream(ancestors.split(",")).map(s -> Long.valueOf(s.trim())).collect(Collectors.toList());
        List<SysDept> deptList = deptMapper.selectDeptByIdsAndType(deptIds, 1);
        if (CollectionUtils.isEmpty(deptList)){
            throw new BaseException("该部门不存在剧院下,请核实后再编辑");
        }
        //降序排列
        List<SysDept> collect = deptList.stream().sorted(Comparator.comparing(SysDept::getOperaLevel).reversed()).collect(Collectors.toList());
       return collect.get(0);
    }

    /**
     * 部门列表
     *
     * @param dept
     * @return
     */
    @Override
    public List<SysDept> selectDeptLists(SysDept dept) {
        return deptMapper.selectByOpreaId(dept.getOperaId(),dept.getDeptName(),dept.getStatus());
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t)
    {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    public List<SysDept> getChildList(List<SysDept> list, SysDept t)
    {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext())
        {
            SysDept n = (SysDept) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t)
    {
        return getChildList(list, t).size() > 0;
    }
}
